﻿google.load("maps", "2.x");
var map;
var mapMarker;
var geocoder;
var geocoderMark;
var filter = "";

/* WATERMARK RELATED PLUGIN*/
(function ($) {
    var map = new Array();
    $.Watermark = {
        ShowAll: function () {
            for (var i = 0; i < map.length; i++) {
                if (map[i].obj.val() == "") {
                    map[i].obj.val(map[i].text);
                    map[i].obj.css("color", map[i].WatermarkColor);
                } else {
                    map[i].obj.css("color", map[i].DefaultColor);
                }
            }
        },
        HideAll: function () {
            for (var i = 0; i < map.length; i++) {
                if (map[i].obj.val() == map[i].text)
                    map[i].obj.val("");
            }
        }
    }

    $.fn.Watermark = function (text, color) {
        if (!color)
            color = "#aaa";
        return this.each(
			function () {
			    var input = $(this);
			    var defaultColor = input.css("color");
			    map[map.length] = { text: text, obj: input, DefaultColor: defaultColor, WatermarkColor: color };
			    function clearMessage() {
			        if (input.val() == text)
			            input.val("");
			        input.css("color", defaultColor);
			    }

			    function insertMessage() {
			        if (input.val().length == 0 || input.val() == text) {
			            input.val(text);
			            input.css("color", color);
			        } else
			            input.css("color", defaultColor);
			    }

			    input.focus(clearMessage);
			    input.blur(insertMessage);
			    input.change(insertMessage);

			    insertMessage();
			}
		);
    };
})(jQuery);

/* WATERMARK RELATED PLUGIN*/

function initialize() {
    map = new GMap2($("#mapDiv").get(0));
    geocoder = new GClientGeocoder();
}

$(document).ready(function () {
    if ($('#mapDiv').length) {
        initialize();
    }
    /*CLUB.ASPX RELATED*/
    if ($('#HomePage').length) {
        setDefault(true);
        $('#load').show('pulsate'); //Add some visulization for loading rather than text(for homepage).
    }
    /*CLUB.ASPX RELATED*/

    //SEARCH FORM RELATED
    $('input:submit').button();

    $('#searchform').submit(function () {
        if ($('#searchtext').css('color') == 'rgb(170, 170, 170)') {
            return false;
        }
        if (filter.indexOf("Location", 0) > -1)
            $('#filter').val(0);  // Search for location
        else if (filter.indexOf("ClubName", 0) > -1)
            $('#filter').val(1);  // Search for Club
        else
            $('#filter').val(-1);   //For no filter

        return true;
    });
    $('#searchtext').Watermark("Search Badminton Clubs based on Location or Club Name");

    $('#searchtext').autocomplete({
        source: function (request, response) {
            $.ajax({
                url: "/Suggest",
                dataType: "json",
                data: {
                    term: request.term
                },
                success: function (data) {
                    response($.map(data, function (item) {
                        filter = "";
                        return {
                            label: item.Value + " <span style='color:grey;float:right'>" + item.Type + "</span>",
                            value: item.Value
                        }
                    }));
                }
            }); // ajax close
        },
        minLength: 2,
        select: function (event, ui) {
            filter = ui.item.label;
        }
    });  // autocomplete close.

    /* Details page related */
    if ($('#detailscontainer').length) {  // run this code only on details page.
        var lat = $('#Lat').val();
        var lon = $('#Lon').val();
        setDefault(false); LoadPins(lat, lon,15);   //Used to load the map and show the pushpins.
    }
    /* Details page related */

    /* Search Page */
    if ($('#SearchPage').length) {
        setDefault(false);
        LoadSearchPins();
        makeScrollable("div.showresults", "div.results");
    }
    /* Search Page */

    /* Create Page */
    $('#Others').hide();
    $('#lblSurface').hide();

    $('select').change(function (data) {
        if (this.value == "5") {
            //show text box.
            $('#Others').show();
            $('#lblSurface').show();
        } else {
            $('#Others').hide();
            $('#lblSurface').hide();
        }

    });
    /* Create Page */
    if ($('#Country').length) {
        setDefault(false);
    }
    var addressEntered = "";
    $('#Country').blur(function () {
        addressEntered = $('#Country').val();
        if (addressEntered != "") {
            geocoder.getLocations(addressEntered, updateMap);
        }
    });

    $('#State').blur(function () {
        addressEntered = $('#State').val() + "," + addressEntered;
        if (addressEntered != "") {
            geocoder.getLocations(addressEntered, updateMap);
        }        
    });

    $('#City').blur(function () {
        addressEntered = $('#City').val() + "," + addressEntered;
        if (addressEntered != "") {
            geocoder.getLocations(addressEntered, updateMap);
        }
    });

    $('#Address').blur(function () {
        addressEntered = $('#Address').val() + "," + addressEntered;
        if (addressEntered != "") {
            geocoder.getLocations(addressEntered, updateMap);                      
        }
    });
});

function LoadPins(lat, lon,zoom) {  // Called on the details page to load pushpins.
    
    map.clearOverlays();
    var latlng = new GLatLng(lat, lon);
    var gmarker = new GMarker(latlng);
    map.addOverlay(gmarker);
    map.setCenter(latlng, zoom);
    map.setUIToDefault();
    
}

/* Create Page related */
function fillAddress() {
    var addr = place.address;
    var lon = place.Point.coordinates[0];
    var lat = place.Point.coordinates[1];
    addr = addr.split(",");
    addr = addr.reverse(); //reverse the array as we get the last parameter as country, then state and city.
    switch (addr.length) {
        case 0: //do nothing in case of array size zero
            break;
        case 1:
            $('#Country').val(addr[0]).css('color', 'black');
            break;
        case 2:
            $('#Country').val(addr[0]).css('color', 'black');
            $('#State').val(addr[1]).css('color', 'black');
            break;
        case 3:
        default:
            $('#Country').val(addr[0]).css('color', 'black').focus();
            $('#State').val(addr[1]).css('color', 'black').focus();
            $('#City').val(addr[2]).css('color', 'black').focus();
            //for address
            var address = "";
            $.each(addr, function (index, addr) {
                if (index > 2) {
                    address = addr + "," + address;
                }
            });
            $('#Address').val(address).css('color', 'black');  //set font color to black an focus on the text box.
            $('#Latitude').val(lat);
            $('#Longitude').val(lon);            
            break;
    }

    //update the original map on the create page
    LoadPins(lat, lon,10);
}

function noresult(str) {
    if (str != null) {
        $('#showresults').html('<div class=\"noresult\">'+
                    '<div class=\"red\">'+
                        'No clubs found for "'+str+'"</div>'+
                    '<div class=\"noresultbut\">'+
                        '<div class=\"grn button mt25\">'+
                            '<a href=\"/Index\" class=\"green\" title=\"Check all clubs in our list\"><b>Check All Clubs»</b></a>'+
                        '</div>'+                        
                    '</div>'+
                '</div>');
        geocoder.getLocations(str, function (response) {   //set location on map as the searched city.
            if (response || response.Status.code == 200) {
                var place = response.Placemark[0];
                var point = new GLatLng(place.Point.coordinates[1],
                       place.Point.coordinates[0]);
                map.setCenter(point, 12);
            }

        });
    }
}

function makeScrollable(wrapper, scrollable) {
    var wrapper = $(wrapper), scrollable = $(scrollable);    
    wrapper.mousemove(function (e) {
        // height of area at the top at bottom, that don't respond to mousemove
        var inactiveMargin = 100;
        // Cache for performance
        var wrapperWidth = wrapper.width();
        var wrapperHeight = wrapper.height();
        // Using outer height to include padding too
        var scrollableHeight = scrollable.outerHeight() + 2 * inactiveMargin;
        // Do not cache wrapperOffset, because it can change when user resizes window
        // We could use onresize event, but it&#39;s just not worth doing that             

        //When user move mouse over menu            
        var wrapperOffset = wrapper.offset();
        // Scroll menu
        var top = (e.pageY - wrapperOffset.top) * (scrollableHeight - wrapperHeight) / wrapperHeight - inactiveMargin;

        if (top < 0) {
            top = 0;
        }
        wrapper.scrollTop(top);
    });
}

function addAddressToMap(response) {
    mapMarker.clearOverlays();
    var point;
    var isDefault = false;
    if (!response || response.Status.code != 200) {
        if (google.loader.ClientLocation != null) {
            point = new GLatLng(google.loader.ClientLocation.latitude, google.loader.ClientLocation.longitude);
        }
        else {
            point = new GLatLng(0, 0);
            isDefault = true;
        }
    }
    else {
        place = response.Placemark[0];
        point = new GLatLng(place.Point.coordinates[1],
                           place.Point.coordinates[0]);
    }

    $('.mapoptions').show().dialog('open');

    mapMarker.setUIToDefault();
    if (!isDefault)
    {
        marker = new GMarker(point, { draggable: true });
        mapMarker.addOverlay(marker);
        GEvent.addListener(marker, "click", function () {
            marker.openInfoWindowHtml(place.address + '<br>' +
                    '<b>Country :</b> ' + place.AddressDetails.Country.CountryNameCode);
        });
        GEvent.addListener(marker, "dragstart", function () {
            mapMarker.closeInfoWindow();
        });

        mapMarker.setCenter(point, 11);
    }
    else {
        marker = new GMarker(point, { draggable: true });
        mapMarker.setCenter(point, 2);
    }
    GEvent.addListener(marker, "dragend", function () {
        geocoder.getLocations(marker.getPoint(), function (response) {
            if (response || response.Status.code == 200) {
                place = response.Placemark[0];
                marker.openInfoWindowHtml(place.address + "<p><b>Click Add button to use this as the new address for the club.</b></p>");
            }
        });

    });

    mapMarker.checkResize();
}

function updateMap(response) {
    map.clearOverlays();
    var point;
    place = response.Placemark[0];
    //Set the lat/lon hidden fields
    $('#Latitude').val(place.Point.coordinates[1]);
    $('#Longitude').val(place.Point.coordinates[0]);
    point = new GLatLng(place.Point.coordinates[1],
                        place.Point.coordinates[0]);                       

    map.setUIToDefault();
    
    marker = new GMarker(point, { draggable: true });
    map.addOverlay(marker);
    GEvent.addListener(marker, "click", function () {
        marker.openInfoWindowHtml(place.address + '<br>' +
                '<b>Country :</b> ' + place.AddressDetails.Country.CountryNameCode);
    });
    GEvent.addListener(marker, "dragstart", function () {
        map.closeInfoWindow();
    });
    map.setCenter(point, 12);
    var setNewLoc = false;
    GEvent.addListener(marker, "dragend", function () {
        geocoder.getLocations(marker.getPoint(), function (response) {
            if (response || response.Status.code == 200) {
                place = response.Placemark[0];                
            }
        });

    });
    //enable infotext
    
}

function showHelp() {
    $('.help').dialog({
        show: 'blind',
        hide: 'drop',
        width: 500,
        height: 250,
        resizable: false,
        title: "Why?"
    });
}

function rgbToHex(rgb) {
    if (rgb.match(/^#[0-9A-Fa-f]{6}$/)) { //FF gave color in rgb and IE gave in hex.
        return rgb;                       //This function takes care of both cases and converts rgb to hex value.
    }
    var rgbvals = /rgb\((.+),(.+),(.+)\)/i.exec(rgb);
    if (!rgbvals) {
        return '#aaaaaa';
    }
    var rval = parseInt(rgbvals[1]);
    var gval = parseInt(rgbvals[2]);
    var bval = parseInt(rgbvals[3]);
    var pad = function (value) {
        return (value.length < 2 ? '0' : '') + value;
    }
    return '#' + pad(rval.toString(16)) + pad(gval.toString(16)) + pad(bval.toString(16));
}


function loadLocation() {
    var club_details = "";
    mapMarker = new GMap2($("#mapMarker").get(0));
    geocoderMark = new GClientGeocoder();    

    if (rgbToHex($('#Address').css('color')) == '#aaaaaa') { //If address is not entered
        if (rgbToHex($('#City').css('color')) == '#aaaaaa') { //and city is not entered
            if (google.loader.ClientLocation != null) { //then redirect map to the default location.
                club_details = new GLatLng(google.loader.ClientLocation.latitude, google.loader.ClientLocation.longitude);
            }
            else {
                club_details = new GLatLng(0, 0);
            }

        }
        else { //if only city is entered then show map to the city.
            club_details = $('#City').val();
        }
    }
    else { // Join all the details and show map accordingly.

        club_details = $('#Address').val() + ',' + $('#City').val() + ',' + $('#State').val() + ',' + $('#Country').val();
    }    
    geocoderMark.getLocations(club_details, addAddressToMap);
    $('.mapoptions').dialog({
        autoOpen: false,
        show: 'blind',
        width: 600,
        height: 500,
        resizable: false,
        title: "Preview Club Location",
        buttons: { "Cancel": function () { $(this).dialog("close"); }, "Add": function (event, ui) { fillAddress(); $(this).dialog("close"); } }
    });
}

function addWatermark() {
    $('#ClubName').Watermark("E.g: Badminton Sports Club");
    $('#Country').Watermark("E.g: United States");
    $('#State').Watermark("E.g: California");
    $('#City').Watermark("E.g: San Francisco");
    $('#Address').Watermark("E.g: 4356, 34th St...");
    $('#Website').Watermark("E.g: www.example.com");
    $('#From_Email').Watermark("E.g: email_address@example.com");
    $('#PhoneNumber').Watermark("E.g: 555-555-5555");
    $('#Email').Watermark("E.g: club_email_address@club.com");
    $('#Fees').Watermark("E.g: $50 - Adult, $35 - Kids, per month etc...");
    $('#Timings').Watermark("E.g: Morning 7-9 Weekdays,7AM-10PM Weekends....");
    $('#Description').Watermark("E.g: Any other facilities in the club/courts like Gym, Tennis courts or any generic details regarding the court other than surface.");

}

/* Create Page related */

function setDefault(flag) {
    var defaultLoc;
    if (google.loader.ClientLocation) {                
        defaultLoc = new GLatLng(google.loader.ClientLocation.latitude, google.loader.ClientLocation.longitude);        
        map.setCenter(defaultLoc, 10);        
    }
    else {
        defaultLoc = new GLatLng(0, 0);
        map.setCenter(defaultLoc, 1);
    }
    map.setUIToDefault();   
    var bounds = map.getBounds();
    var southWest = bounds.getSouthWest();
    var northEast = bounds.getNorthEast();    
    if (flag) {
        $.post("/ClubsByRegion", { latWest: southWest.lat(), latEast: northEast.lat(), lngWest: southWest.lng(), lngEast: northEast.lng() }, function (data, success) {            
            if (data.length > 0) {
                $.each(data, function (key, value) {
                    // Create a lettered icon for this point using our icon class

                    var letter = String.fromCharCode("A".charCodeAt(0) + key);
                    var letteredIcon = new GIcon(G_DEFAULT_ICON);
                    letteredIcon.image = "http://www.google.com/mapfiles/marker" + letter + ".png";

                    // Set up our GMarkerOptions object
                    markerOptions = { icon: letteredIcon };
                    var latlng = new GLatLng(value.Latitude, value.Longitude);
                    var gmarker = new GMarker(latlng, markerOptions);
//                    GEvent.addListener(gmarker, "click", function () {
//                        gmarker.openInfoWindowHtml("<b>Club : " + value.ClubName + "</b><p><b>Address : " + value.Address + "," + value.City.CityName + "</b></p><span class=\"space\"><a href=\"Club/Details/" + value.ClubName + "\">More Info</a></span>||<span class=\"space\"><a href=\"http://maps.google.com/maps?daddr=" + value.Latitude + "," + value.Longitude + "&saddr=\" target=\"_blank\">Directions</a></span>");
//                    });
                    map.addOverlay(gmarker);
                    showResults(data);
                });
            }
            else {          //In case there is no data show a message.
                noresult(google.loader.ClientLocation.address.city);
            }
        });
    }
}

function showResults(data) {
    $('#mapDiv').animate({
        width: 600
    }, 1000, function () {
        var resultHtml = "";
        $.each(data, function (index, club) {
            var letter = String.fromCharCode("A".charCodeAt(0) + index);
            var imageurl = "http://www.google.com/mapfiles/marker" + letter + ".png";
            resultHtml += "<div class=\"clubresults\"><div class=\"floatl mart5\"><img src=\"" + imageurl + "\"/></div>" +
                            "<span class=\"name\"><a href=\"/Details/"+club.ClubName.replace(/ /g,"-")+"\">"+club.ClubName+"</a></span>"+
                            "<div class=\"address\">"+club.Address+
                                "<div>"+club.City.CityName+","+club.City.State.StateName+"-"+club.Zipcode+"</div>"+
                            "</div>"+                            
                            "<div class=\"buttonresult\">"+                                
                                    "<a class=\"green\" href=\"/Details/"+club.ClubName.replace(/ /g,"-")+"\">More info »</a>"+                                
                            "</div>"+                                                     
                        "</div>";
        });
        $('#showresults').show();
        $('#showresults').html("<div class=\"results\">" + resultHtml + "</div>");
        makeScrollable("div.showresults", "div.results");
    });
    map.setUIToDefault();
}

function reportProblem() {
    $('.report').dialog({ show: 'blind',
        //hide: 'drop',
        width: 350,
        height: 250,
        resizable: false,
        title: "Let us know more about this club",
        buttons: { Report: function (event, ui) {
            var str = $('textarea').val();
            var clubId = $('#ClubID').val();
            if ($.trim(str) == '')
                alert('Please let us know the issue with the information');
            else {
                $.ajax({
                    url: '/ReportProblem',
                    data: {
                        clubId: clubId,
                        problem: $('textarea').val()
                    }
                });
                alert('Thanks for reporting. We will look into it.');
                $('.report').dialog('close');
            }
        }
        }
    });
    
}

function addInfoMarker(marker, club) {    
    GEvent.addListener(marker, "click", function() {
        var clubInfo = "<b>Club : </b>" + club.ClubName + "<p><b>Address : </b></p>" + club.Address+"<p><b><a href=\"Club/Details/"+club.ClubName+"\">More Info</a></b></p>";  
        marker.openInfoWindowHtml(clubInfo);
    });

}